var AdminSystem_PlayerDatas = [];

class AdminSystem_PlayerData {
	IsAdmin = false;
}

World.Core.AddListener("OnPlayerComplete", function (player) {
	if (AdminSystem_PlayerDatas[player.ID] == null) {
		AdminSystem_PlayerDatas[player.ID] = new AdminSystem_PlayerData();
	}
}, -1);

World.Core.AddListener("OnPlayerCommand", function (player, command, args) {
	if (command == "admin") {
		Debug.LogError("登陆ADMIN指令");

		if (args != null) {
			if (AdminSystem_PlayerDatas[player.ID].IsAdmin) {
				player.Message("你已经登陆管理员！");
				return;
			}

			//使用本地[Host/SaveData/SaveData_100.json]目录的存档100作为密码文件，防止同步时读取管理员密码
			let password = World.Core.GetSaveItem("AdminSystemPassword", 100, "admin");

			if (args == password) {
				AdminSystem_PlayerDatas[player.ID].IsAdmin = true;

				player.Message("登陆完成！");
			} else {
				player.Message("无效的Admin密码！");
			}
		} else {
			player.Message("需要输入Admin密码（'/admin password'）");
		}
	}
	else if (command == "isadmin") {
		if (AdminSystem_PlayerDatas[player.ID].IsAdmin) {
			player.Message("你已经登陆管理员！");
		} else {
			player.Message("你还没有登录管理员！");
		}
	} else {
		if (AdminSystem_PlayerDatas[player.ID].IsAdmin) {
			if (OnAdminCommand(player, command, args) == false) {
				player.Message("没有找到合适的管理员指令！");
			}
		}
	}
}, -1);

function OnAdminCommand(player, command, args) {
	//Only admin user
	if (command == "kick") {
		if (GetArgsSpaceNum(args) == 1) {
			let plr = World.Player.Search(args);

			if (plr != null) {
				plr.Kick();
				World.Core.Message(GetLanguageText("AdminSystem.KickPlayer", plr.Name));
			} else {
				SendMessage(player, "AdminSystem.InvalidTarget");
			}
		} else {
			SendMessage(player, "AdminSystem.InvalidArgs", " (kick [player])");
		}

		return true;
	} else if (command == "pig") {
		if (GetArgsSpaceNum(args) == 1) {
			let plr = World.Player.Search(args);

			if (plr != null) {
				World.Core.Message(`把${plr.Name}变成小猪！！`);

				if (plr.Character) plr.Character.Remove();

				let chara = World.Character.Create(2, plr.Pos, 0);
				if (chara) {
					plr.SetEntity(chara, true);
				}
			} else {
				SendMessage(player, "AdminSystem.InvalidTarget");
			}
		} else {
			SendMessage(player, "AdminSystem.InvalidArgs", " (pig [player])");
		}

		return true;
	}

	return false;
}

function GetArgsSpaceNum(args) {
	if (args == null || args == "") return 0;

	let splitLength = args.split(" ").length;
	return splitLength == 0 ? 1 : splitLength;
}

function GetTok(string, separator, index) {
	let splits = string.split(separator);
	return splits[index];
}

function SendMessage(player, key, addString = "") {
	player.Message(GetLanguageText(key) + addString);
}